package action;

import global.Constants;
import global.beanUtils.BeanUtils;
import global.security.SessionUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.FeedFavoriteService;
import service.FeedService;
import util.FileUtils;
import util.MessageUtils;
import util.ServletHelp;
import util.StringUtils;
import domain.Feed;
import domain.FeedFavorite;


/**
 * 订阅Action类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class FeedAction extends BaseAction {
	/**
	 * 订阅Service
	 * */
	private FeedService feedService = null;
	
	/**
	 * 收藏订阅Service
	 * */
	private FeedFavoriteService feedFavoriteService = null;
	
	
	/**
	 * @param feedService the feedService to set
	 */
	public void setFeedService(FeedService feedService) {
		this.feedService = feedService;
	}
	
	
	/**
	 * @param feedFavoriteService the feedFavoriteService to set
	 */
	public void setFeedFavoriteService(FeedFavoriteService feedFavoriteService) {
		this.feedFavoriteService = feedFavoriteService;
	}

	/**
	 * 获得订阅分类树
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward getFeedTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数
		String parentId = request.getParameter("parentId");
		JSONArray res = feedService.selectFeedForTree(parentId);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 保存订阅
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数设定
		Map map = request.getParameterMap();
		Feed feed = new Feed();
		BeanUtils.populate(feed, map);
		feed.setStatus(Constants.STATUS_1);

		// 保存
		String feedId = request.getParameter("feedId");
		if (StringUtils.isNotEmpty(feedId)) {
			// 更新订阅
			feedService.update(feed);
		} else {
			// 添加订阅
			feedService.insert(feed);
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 删除订阅
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 订阅ID
		String feedId = request.getParameter("feedId");
		// 删除订阅
		if (StringUtils.isNotEmpty(feedId)) {
			
			// 订阅文件的保存路径
			String feedFilePath = ServletHelp.getRealPath(request,
					MessageUtils.setParamMessage(Constants.FEED_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
			feedService.delete(Integer.parseInt(feedId), feedFilePath);
		}
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 发送订阅
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward sendFeed(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 邮箱地址
		String emails = request.getParameter("emails");
		// 标题
		String title = request.getParameter("title");
		// 链接
		String link = request.getParameter("link");
		// 摘要
		String description = request.getParameter("description");

		// 发送订阅
		boolean hasSend = ServletHelp.sendEmail(emails, title, "<a href='"+link+"'>"+title+"</a><br/>"+description);

		// 构造查询结果
		JSONObject res = new JSONObject();
		if(hasSend){
			res.put("success", true);
		}else{
			res.put("success", false);
		}
		String result = res.toString();
		// 返回查询结果
		ServletHelp.outRequestForJson(request, response, result);
		return null;
	}
	
	/**
	 * 收藏订阅
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward favorite(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数设定
		Map map = request.getParameterMap();
		FeedFavorite feedFavorite = new FeedFavorite();
		BeanUtils.populate(feedFavorite, map);
		feedFavorite.setDelflag(Constants.DEL_FLAG_1);
		feedFavorite.setStatus(Constants.STATUS_1);
		
		// 添加订阅
		feedFavoriteService.insert(feedFavorite);

		// 构造查询结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		String result = res.toString();
		// 返回查询结果
		ServletHelp.outRequestForJson(request, response, result);
		return null;
	}

	/**
	 * 更新订阅信息
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward refreshFeed(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 订阅地址
		String feedId = request.getParameter("feedId");
		if(StringUtils.isNotEmpty(feedId)){
			// 订阅文件的保存路径
			String feedFilePath = ServletHelp.getRealPath(request,
					MessageUtils.setParamMessage(Constants.FEED_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
			feedService.refreshFeed(Integer.parseInt(feedId), feedFilePath);
		}
		// 构造查询结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		String result = res.toString();
		// 返回查询结果
		ServletHelp.outRequestForJson(request, response, result);
		return null;
	}

	/**
	 * 根据URL获得订阅
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward getFeed(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 订阅地址
		String feedId = request.getParameter("feedId");
		String feedUrl = request.getParameter("feedUrl");
		if(StringUtils.isNotEmpty(feedId) && StringUtils.isNotEmpty(feedUrl)){
			// 订阅文件的保存路径
			String feedFilePath = ServletHelp.getRealPath(request,
					MessageUtils.setParamMessage(Constants.FEED_FILE_PATH, new String[]{SessionUtils.getCurrentUserId()}))+"/"+feedId+".xml";
			// 更新订阅
			try {
				FileUtils.saveFileByUrl(feedUrl, feedFilePath);
			} catch (FileNotFoundException e) {// 文件不存在时正常返回缓存文件
			} catch (ConnectException e){// 网络连接异常时正常返回缓存文件
			}
			// 返回xml格式文件
			response.setContentType("application/xml");
			// 输入流
			FileInputStream fis = null;
			// 输出流
			BufferedOutputStream bos = null;
		    try {
		    	fis = new FileInputStream(new File(feedFilePath));
		        bos = new BufferedOutputStream(response.getOutputStream());
		        byte[] buff = new byte[2048];
		        int bytesRead;
		        while(-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
		            bos.write(buff,0,bytesRead);
		        }
		    } finally {
		    	// 关闭流
		        if (fis != null)
		        	fis.close();
		        if (bos != null)
		            bos.close();
		    }
		}
		return null;
	}
	
	
	/**
	 * 导入订阅列表(OPML)
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward importOpml(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获得参数
		String feedId = request.getParameter("feedId");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items = null;
		// 得到所有的文件：
		items = (List) upload.parseRequest(request);
		Iterator it = items.iterator();
		InputStream in = null;
		while (it.hasNext()) {
			// 依次处理每一个文件：
			FileItem fi = (FileItem) it.next();
			if ("feedFile".equals(fi.getFieldName())) {
				in = fi.getInputStream();
			}else if("feedId".equals(fi.getFieldName())){
				
			}
		}
		
		// 导入订阅列表
		if(StringUtils.isNotEmpty(feedId) && null!=in){
			feedService.importOpml(feedId, in);
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		response.getWriter().print(res);
		return null;
	}
	
	
	/**
	 * 导出订阅列表
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward exportOpml(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 订阅目录ID
		String feedId = request.getParameter("feedId");
		if(StringUtils.isNotEmpty(feedId)){
			// 文件的保存路径
			String filePath = ServletHelp.getRealPath(request, Constants.TEMP_FILE_PATH +"/" + "anynote-reader-opml.xml");
			// 生成订阅列表OPML
			feedService.exportOpml(feedId, filePath);
			// 下载文件
			ServletHelp.download(mapping, form, request, response, filePath, "anynote-reader-opml.xml");
		}
		return null;
	}
}
